import type { NodeListItem } from '@/apis/model/node'
import type { latestVersionInfo } from '@/apis/model/version'
import {
  deleteApiNodeApi,
  postApiNodeControlApi,
  updateApiNodeApi
} from '@/apis/modules/node/node'
import {
  getApiNodeInstallCommandApi,
  getApiNodeVersionLatestApi,
  updateApiNodeVersionSwitchApi
} from '@/apis/modules/resolve/version'
import { NODE_OPERATIONS } from '@/constants'
import {
  Form,
  FormItem,
  Select,
  Input,
  Button
} from '@arco-design/web-vue'
import { useClipboard } from '@vueuse/core'

import type { JSX } from 'vue/jsx-runtime'
import IconCopy from '~icons/icons/copy'
export default function useCommand(reload: () => void) {
  const handleCommand = (
    command: string,
    ids: string[],
    row?: NodeListItem
  ) => {
    const {
      getVersionDescription,
      switchVersion,
      singleVersionChange
    } = versionControl(reload)
    const controlNode = (type: NODE_OPERATIONS, content: string) => {
      const fn = () =>
        postApiNodeControlApi({ control_type: type, ids: ids }).then(() => {
          ToastUtils.success('操作成功')
          reload()
        })
      if ([NODE_OPERATIONS.STOP, NODE_OPERATIONS.RELOAD].includes(type)) {
        CloudModal.error(
          {
            maskClosable: false,
            content: content
          },
          fn
        )
      } else {
        CloudModal.confirm(
          {
            maskClosable: false,
            content: content
          },
          fn
        )
      }
    }
    const map: Record<string, () => void> = {
      start: () => {
        // 启用
        const content = `启用所选 ${ids.length} 个节点，开始向终端用户提供服务，确认继续？`
        controlNode(NODE_OPERATIONS.START, content)
      },
      startOne: () => {
        // 启用
        const content = `启用节点 “${row?.name}” ，确认继续？`
        controlNode(NODE_OPERATIONS.START, content)
      },
      stop: () => {
        const content = `停用所选 ${ids.length} 个节点，停止向终端用户提供服务，确认继续？`
        // 停用
        controlNode(NODE_OPERATIONS.STOP, content)
      },
      stopOne: () => {
        // 停用
        const content = `停用节点 “${row?.name}” ，确认继续？`
        controlNode(NODE_OPERATIONS.STOP, content)
      },
      reload: () => {
        // 重启
        const content = `重启所选 ${ids.length} 个节点，确认继续？`
        controlNode(NODE_OPERATIONS.RESTART, content)
      },
      reloadOne: () => {
        // 重启
        const content = `重启节点 “${row?.name}” ，确认继续？`
        controlNode(NODE_OPERATIONS.RESTART, content)
      },
      join: () => {
        const fn = () =>
          updateApiNodeApi({ id: ids[0] as string, enable_resolve: true }).then(
            () => {
              ToastUtils.success('操作成功')
              reload()
            }
          )
        // 加入解析
        CloudModal.confirm(
          {
            maskClosable: false,
            content: `将节点 IP “${row?.ips ? row?.ips[0] : ''}” 加入解析链路，确认继续？`
          },
          fn
        )
      },
      remove: () => {
        const fn = () =>
          updateApiNodeApi({
            id: ids[0] as string,
            enable_resolve: false
          }).then(() => {
            ToastUtils.success('操作成功')
            reload()
          })

        // 移除解析
        CloudModal.error(
          {
            maskClosable: false,
            content: `将节点 IP “${row?.ips ? row?.ips[0] : ''}” 从解析链路中移除，确认继续？`
          },
          fn
        )
      },
      version: async () => {
        let info = {} as latestVersionInfo
        info = await getVersionDescription(row!.version!)
        const title = ids.length > 1 ? '批量升级版本' : '升级版本'
        // const fn =
        //   ids.length > 1
        //     ? batchChangeVersion(ids.length)
        //     : singleVersionChange(descriptions, row?.version)

        const fn = singleVersionChange(info?.imprint, info?.version, ids.length)
        CloudModal.normal(
          {
            title: title,
            maskClosable: false,
            width: 480,
            content: fn
          },
          () => switchVersion(ids)
        )
      },
      config: () => {
        // 批量同步配置
        const fn = () =>
          postApiNodeControlApi({
            control_type: NODE_OPERATIONS.SYNC,
            ids: ids
          }).then(() => {
            ToastUtils.success('操作成功')
            reload()
          })
        CloudModal.error(
          {
            maskClosable: false,
            content: () => (
              <div class="flex flex-col gap-y-6 text-1">
                <span>
                  {/* 该操作会重置所选节点的配置，清空并重新生成相关联站点配置，确认继续？ */}
                  重新生成并下发所选 {ids.length} 个节点的相关配置，确认继续？
                </span>
                <span class="text-4">
                  *注意：若涉及到大量节点和站点时可能耗时较长
                </span>
              </div>
            )
          },
          fn
        )
      },
      cache: () => {
        // 清除缓存
        const fn = () =>
          postApiNodeControlApi({
            control_type: NODE_OPERATIONS.PURGE,
            ids: ids
          }).then(() => {
            ToastUtils.success('操作成功')
            reload()
          })
        CloudModal.error(
          {
            maskClosable: false,
            content: `清除所选 ${ids.length} 个节点的所有缓存，缓存将在数分钟后失效，确认继续？`
          },
          fn
        )
      },
      delete: () => {
        const nameVerification = reactive({ name: '' })
        const disabled = computed(() => nameVerification.name !== row?.name)
        const loading = ref(false)
        // 删除节点
        const fn = () => {
          loading.value = true
          return deleteApiNodeApi({ id: ids[0] as string })
            .then(() => {
              ToastUtils.success('操作成功')
              modalReturn.close()
              reload()
            })
            .finally(() => {
              loading.value = false
            })
        }

        const modalReturn = CloudModal.error(
          {
            maskClosable: false,
            //content: text,
            okText: '确定',
            footer: () => {
              return row?.installed ? (
                <div class="flex  justify-end">
                  {/* <Button onClick={() => modalReturn.close()} class="mr-4">
                    取消
                  </Button> */}
                  <Button
                    status="danger"
                    disabled={disabled.value}
                    class={disabled.value ? 'bg-[#FBACA3]! w-full' : 'w-full'}
                    style={disabled.value ? 'border:1px solid #FBACA3' : ''}
                    onClick={() => fn()}
                    loading={loading.value}>
                    我已知晓后果并确认删除
                  </Button>
                </div>
              ) : null
            },
            content: () =>
              row?.installed ? (
                <div class="flex flex-col gap-y-6 text-1 w-full">
                  <span class={`text-[#1D2129] `}>
                    删除并卸载节点 “{row?.name}” ，此操作无法撤销。
                  </span>
                  <div class="w-full">
                    <Form layout="vertical" model={nameVerification}>
                      <FormItem
                        asteriskPosition="end"
                        field="name"
                        validateTrigger={'blur'}
                        hide-asterisk
                      // rules={[
                      //   {
                      //     required: true,
                      //     validator(value, cb) {
                      //       if (!value) {
                      //         return cb('请输入提示内容')
                      //       }
                      //       if (value !== row?.name) {
                      //         return cb('请输入提示内容')
                      //       }
                      //       return cb()
                      //     }
                      //   }
                      // ]}
                      >
                        {{
                          label: () => (
                            <span class="text-4">
                              请输入「
                              <span class={'text-red-500'}>{row?.name}</span>
                              」确认
                            </span>
                          ),
                          default: () => (
                            <Input
                              class="w-full"
                              modelValue={nameVerification.name}
                              maxLength={32}
                              onInput={(v) => {
                                nameVerification.name = v
                              }}
                              placeholder=""></Input>
                          )
                        }}
                      </FormItem>
                    </Form>
                  </div>
                </div>
              ) : (
                `确认删除节点 “${row?.name}” ？`
              )
          },
          fn
        )
      },
      install_script: async () => {
        const { renderInstallScript, getScript, formState } = getInstallScript()
        await getScript(ids[0] as string)
        if (!formState.url) return false
        CloudModal.normal({
          title: '安装命令',
          maskClosable: false,
          footer: false,
          width: 600,
          content: renderInstallScript
        })
      }
    }
    map[command]()
  }
  return { handleCommand }
}

/**
 *
 * 安装脚本弹窗
 */
function getInstallScript() {
  const formState = reactive({ url: '' })
  const { copy } = useClipboard({ legacy: true })
  const handleCopy = (content: string) => {
    copy(content)
    ToastUtils.success('复制成功')
  }
  async function getScript(id: string) {
    return getApiNodeInstallCommandApi({
      id: id
    })
      .then((res) => {
        formState.url = res.command ?? ''
      })
      .catch(() => {
        return true
      })
  }
  const renderInstallScript = () => (
    <div class="flex flex-col gap-y-6 w-full text-1">
      {/* <div class="flex justify-between">
        <span>请复制命令在目标节点目标服务器中进行安装</span>
        <span
          class="flex gap-x-6px items-center text-primary cursor-pointer"
          onClick={() => handleCopy(formState.url ?? '')}>
          <IconCopy />
          复制
        </span>
      </div> */}
      <div class="bg-#1D2129 rounded p-4 text-white flex justify-between gap-4">
        <div>{formState.url}</div>
        <div>
          <div
            class="flex gap-x-6px items-center text-white cursor-pointer w-20px"
            onClick={() => handleCopy(formState.url ?? '')}>
            <IconCopy />
          </div>
        </div>
      </div>
    </div>
  )

  return {
    formState,
    getScript,
    renderInstallScript
  }
}

/**
 * 版本切换弹窗
 * @param reload 重新获取列表数据
 * */
function versionControl(reload: () => void) {
  const versionsOpt = ref<LabelValue[]>([])

  const targetVersion = reactive({ version: '', id: '' })
  const targetDesc = ref('')
  // 版本说明
  function versionDescription(des?: string) {
    return (
      <FormItem label="版本说明" class="version-item">
        <div
          class={[
            'text-4 text-wrap whitespace-pre-line max-h-[200px] overflow-auto w-full',
            { 'text-2!': des }
          ]}>
          {des && des !== '-' ? des : '此版本暂无说明'}
        </div>
      </FormItem>
    )
  }

  // 获取版本描述
  async function getVersionDescription(version: string): Promise<latestVersionInfo> {
    try {
      if (!version) return { version: '', imprint: '' }
      const res = await getApiNodeVersionLatestApi({ version })
      console.log('res: ', res);
      return res || { version: '', imprint: '' }
    } catch (error) {
      console.error(error)
      return { version: '', imprint: '' }
    }
  }
  const versionChange = async (id: string) => {
    targetVersion.id = id
    const version =
      versionsOpt.value.find((item) => item.value === id)?.label ?? ''
    const res = await getApiNodeVersionLatestApi({ version })
    targetDesc.value = res.imprint
  }
  // 批量切换版本
  const batchChangeVersion = (num?: number) => {
    const node = (
      <Form layout="vertical" model={targetVersion}>
        <FormItem
          asteriskPosition="end"
          label="切换版本"
          required
          field="id"
          hide-asterisk>
          <Select
            modelValue={targetVersion.id}
            options={versionsOpt.value}
            placeholder="请选择版本"
            onChange={(v) => versionChange(v as string)}></Select>
        </FormItem>
        {versionDescription(targetDesc.value)}
      </Form>
    )
    return num ? (
      <div class="w-full">
        <div class="mb-2 text-[#8F959E]">将所选 {num} 个节点切换为以下版本</div>
        <div class="w-full min-h-60 flex flex-col rounded-2 gap-y-4 p-4 border border-dashed border-color-3 bg-fill-1">
          {node}
        </div>
      </div>
    ) : (
      node
    )
  }

  function versionWrap(children: () => JSX.Element) {
    return (
      <div class="w-432px min-h-60 flex flex-col rounded-2 gap-y-4 p-4 border border-dashed border-color-3 bg-fill-1">
        {children()}
      </div>
    )
  }
  // 单个版本切换
  const singleVersionChange = (
    desc: string = '',
    currentVersion: string = '',
    num: number
  ) => {
    const currentInfo = () => (
      <>
        <Form model={{}} layout="vertical">
          <FormItem label="版本" class="version-item">
            <span class="text-2">{currentVersion || '-'}</span>
          </FormItem>
          {versionDescription(desc)}
        </Form>
      </>
    )
    return () => (
      <div class="flex flex-col gap-x-4  h-full">
        {num > 1 && (
          <div class="mb-2 text-[#8F959E]">
            将 {num} 个节点升级为以下版本
          </div>
        )}
        {versionWrap(currentInfo)}
      </div>
    )
  }
  const switchVersion = (ids: string[]) =>
    updateApiNodeVersionSwitchApi({
      ids: ids
      //target_id: targetVersion.id
    }).then(() => {
      ToastUtils.success('操作成功')
      reload()
    })
  return {
    singleVersionChange,
    batchChangeVersion,
    switchVersion,
    getVersionDescription
  }
}
